'use strict';

const {
	wxapi
} = require('use-api');

const {
	Controller
} = require('uni-cloud-router');

const dbcmd = uniCloud.database().command;

module.exports = class WxController extends Controller {
	// 获取微信菜单
	async wxMenuGet() {
		let response = {
			code: 1,
			datas: null,
			msg: ''
		};

		const wxMenuUrl =
			'https://api.weixin.qq.com/cgi-bin/get_current_selfmenu_info';

		let start = Date.now();
		// 获取微信 access_token
		const token = await wxapi.get_token();

		const res = await this.curl(wxMenuUrl, {
			nestedQuerystring: true,
			method: 'get',
			headers: {
				'Content-Type': 'application/x-www-form-urlencoded'
			},
			dataType: 'json',
			data: {
				access_token: token
			}
		});
		
		if (res.data.selfmenu_info.button.length) {
			res.data.selfmenu_info.button.forEach(x => {
				if (x.sub_button && x.sub_button.list.length) {
					x.sub_button = x.sub_button.list;
				}
			})
		}

		response.datas = res.data.selfmenu_info;
		response.appid = wxapi.appid;

		let end = Date.now();
		response.code = 0;
		response.msg = `耗时：${end - start}ms`;
		return response;
	}

	// 添加微信菜单
	async wxMenuPost() {
		let response = {
			code: 1,
			datas: null,
			msg: ''
		};

		let {
			button
		} = this.ctx.data;

		// 获取微信 access_token
		const token = await wxapi.get_token();

		const wxMenuUrl =
			`https://api.weixin.qq.com/cgi-bin/menu/create?access_token=${token}`;

		let start = Date.now();

		const res = await this.curl(wxMenuUrl, {
			nestedQuerystring: true,
			method: 'post',
			headers: {
				'Content-Type': 'application/x-www-form-urlencoded'
			},
			dataType: 'json',
			data: button
		});

		response.datas = res.data;

		let end = Date.now();
		response.code = res.data.errcode;
		response.msg = `耗时：${end - start}ms`;
		return response;
	}
}
